<template>
    <div>
      <div class="search">
          <input
            v-model="inputVal"
            class="search-input"
            type="text"
            placeholder="输入城市名或拼音">
      </div>
      <div
        class="search-content"
        ref="search"
        v-show="inputVal">
        <ul>
          <li
            class="search-item border-bottom"
            v-for="item of list"
            :key="item.id"
            @click="clickToChangeCity(item.name)">{{item.name}}</li>
          <li class="search-item border-bottom" v-show="hasNoData">
            没有找到匹配数据
          </li>
        </ul>
      </div>
    </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default ({
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      inputVal: '',
      list: [],
      timer: null
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    inputVal () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.inputVal) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.name.indexOf(this.inputVal) > -1 ||
            value.spell.indexOf(this.inputVal) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 300)
    },
    list () {
      this.$nextTick(function () {
        this.scroll.refresh()
      })
    }
  },
  methods: {
    clickToChangeCity (city) {
      // Vuex 如果组件要修改数据 必须通过dispatch 来触发actions
      this.$store.dispatch('changeCity', city)
      // 修改所在城市之后 进行路由跳转回到首页
      this.$router.push('/')
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
})
</script>

<style lang="stylus" scoped>
@import '~@/assets/varibles.styl'
  .search
    height: .72rem
    background: $bgColor
    padding: 0 .1rem
    .search-input
      box-sizing: border-box
      width: 100%
      height: .62rem
      padding: 0 .1rem
      line-height: .62rem
      text-align: center
      border-radius: .06rem
      color: #666
  .search-content
    overflow: hidden
    position: absolute
    top: 1.58rem
    left: 0
    right: 0
    bottom: 0
    z-index: 1
    .search-item
      line-height: .62rem
      padding-left: .2rem
      background: #fff
      color: #666

</style>
